package com.cheejee.goodscenter.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cheejee.goodscenter.dao.GoodsSpecificMapper;
import com.cheejee.goodscenter.dao.SkuMapper;
import com.cheejee.goodscenter.module.entity.GoodsSpecific;
import com.cheejee.goodscenter.service.GoodsSpecificService;
import com.cheejee.goodscenter.service.exception.CheckException;
import com.cheejee.goodscenter.service.exception.DataNotExistException;
import com.cheejee.goodscenter.service.exception.DuplicateException;
import com.cheejee.goodscenter.validated.Check;
import com.cheejee.goodscenter.validated.InsertGroup;
import com.cheejee.goodscenter.validated.UpdateGroup;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * @author CARRY
 * @Date 2020年10月28日上午11:34:56
 */
@Service
public class GoodsSpecificServiceImpl implements GoodsSpecificService {

	@Resource
	private GoodsSpecificMapper mapper;
	@Resource
	private SkuMapper skuMapper;

	@Override
	public Page<GoodsSpecific> queryGoodsSpecific(Long goodsId, String specificName, String specificValue, int pageNum, int pageSize) {

		return PageHelper.startPage(pageNum, pageSize).doSelectPage(() -> mapper.selectBySelective(goodsId, specificName, specificValue));
	}
	
	@Override
	public GoodsSpecific queryGoodsSpecificById(Long id) {
		
		return mapper.selectByPrimaryKey(id);
	}


	@Override
	@Check(message = { "商品ID不能为空", "添加的商品规格不能为空" }, group = InsertGroup.class)
	public int addGoodsSpecific(List<GoodsSpecific> specific) {
		checkDuplicate(specific);

		return mapper.insertMany(specific);
	}

	@Override
	public int deleteGoodsSpecific(Long... id) {
		List<Long> list = new ArrayList<>();
		for (Long i : id) {
			if (skuMapper.checkUseSpecific(String.valueOf(i)) == 0) {
				list.add(i);
			}
		}

		if (list.size() != id.length) {
			throw new CheckException("已经被SKU使用的规格不能删除");
		}

		return mapper.deleteById(list.toArray(new Long[list.size()]));
	}

	@Override
	@Check(message = "修改的规格不能为空", group = UpdateGroup.class)
	public int changeGoodsSpecific(GoodsSpecific specific) {
		checkExist(specific.getId());
		checkDuplicate(Arrays.asList(specific));

		return mapper.updateByPrimaryKeySelective(specific);
	}

	private void checkExist(Long id) {
		if (mapper.selectByPrimaryKey(id) == null) {
			throw new DataNotExistException("商品规格不存在");
		}
	}
	
	private void checkDuplicate(List<GoodsSpecific> ls) {
		ls.forEach(i -> {
			List<GoodsSpecific> g = mapper.selectBySelective(i.getGoodsId(), i.getSpecificName(), i.getSpecificValue());
			g.forEach(j -> {
				if(j.getId() != i.getId()) {
					throw new DuplicateException("商品规格重复");
				}
			});
		});
	}




}
